package com.piece.core.web.cookie;

import lombok.extern.slf4j.Slf4j;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.net.URLEncoder;

/**
 * Cookie工具类
 */
@Slf4j
public class CookieUtil {

    /**
     * 得到Cookie的值
     *
     * @param cookieName 名称
     * @return
     */
    public static String getCookieValue(HttpServletRequest request, String cookieName) {
        return getCookieValue(request, cookieName, "utf-8");
    }

    /**
     * 得到Cookie的值
     *
     * @param cookieName 名称
     * @param encode     编码格式
     * @return
     */
    public static String getCookieValue(HttpServletRequest request, String cookieName, String encode) {
        Cookie[] cookieList = request.getCookies();
        if (null == cookieList || null == cookieName) {
            return null;
        }
        String retValue = null;
        try {
            for (int i = 0; i < cookieList.length; i++) {
                if (cookieList[i].getName().equals(cookieName)) {
                    retValue = URLDecoder.decode(cookieList[i].getValue(), encode);
                    break;
                }
            }
        } catch (UnsupportedEncodingException e) {
            log.error("获取Cookie异常：{}", e.getMessage());
        }
        return retValue;
    }

    /**
     * 设置Cookie的值,浏览器关闭即失效
     *
     * @param cookieName  名称
     * @param cookieValue 数值
     */
    public static void setCookie(HttpServletRequest request, HttpServletResponse response, String cookieName, String cookieValue) {
        setCookie(request, response, cookieName, cookieValue, -1, true);
    }

    /**
     * 设置Cookie的值,浏览器关闭即失效
     *
     * @param cookieName  名称
     * @param cookieValue 数值
     */
    public static void setCookie(HttpServletRequest request, HttpServletResponse response, String cookieName, String cookieValue, boolean httpOnly) {
        setCookie(request, response, cookieName, cookieValue, -1, httpOnly);
    }

    /**
     * 设置Cookie的值并指定有效时间
     *
     * @param cookieName  名称
     * @param cookieValue 数值
     * @param maxAge      生效时长,单位：秒
     */
    public static void setCookie(HttpServletRequest request, HttpServletResponse response, String cookieName, String cookieValue, int maxAge) {
        setCookie(request, response, cookieName, cookieValue, maxAge, "utf-8");
    }

    /**
     * 设置Cookie的值并指定有效时间
     *
     * @param cookieName  名称
     * @param cookieValue 数值
     * @param maxAge      生效时长,单位：秒
     */
    public static void setCookie(HttpServletRequest request, HttpServletResponse response, String cookieName, String cookieValue, int maxAge, boolean httpOnly) {
        setCookie(request, response, cookieName, cookieValue, maxAge, "utf-8", httpOnly);
    }

    public static final void setCookie(HttpServletRequest request, HttpServletResponse response, String cookieName, String cookieValue, int maxAge, String encode) {
        setCookie(request, response, cookieName, cookieValue, maxAge, encode, true);
    }

    /**
     * 设置Cookie的值，并使其在指定时间内生效
     *
     * @param cookieName  名称
     * @param cookieValue 数值
     * @param maxAge      生效时长,单位：秒
     * @param encode      编码格式
     */
    public static final void setCookie(HttpServletRequest request, HttpServletResponse response, String cookieName, String cookieValue, int maxAge, String encode, boolean httpOnly) {
        try {
            if (null == cookieValue) {
                deleteCookie(request, response, cookieName);
                return;
            } else {
                cookieValue = URLEncoder.encode(cookieValue, encode);
            }
            setCookieWithDomain(request, response, cookieName, cookieValue, maxAge, httpOnly);
        } catch (Exception e) {
            log.error("设置Cookie异常：{}", e.getMessage());
        }
    }

    private static final void setCookieWithDomain(HttpServletRequest request, HttpServletResponse response, String cookieName, String cookieValue, int maxAge) {
        setCookieWithDomain(request, response, cookieName, cookieValue, maxAge, true);
    }

    private static final void setCookieWithDomain(HttpServletRequest request, HttpServletResponse response, String cookieName, String cookieValue, int maxAge, boolean httpOnly) {
        Cookie cookie = new Cookie(cookieName, cookieValue);
        cookie.setMaxAge(maxAge);
        if (null != request) {
            // 设置域名的cookie
            String domainName = getDomainName(request);
            if (domainName != null && !"localhost".equals(domainName) && !"127.0.0.1".equals(domainName)) {
                cookie.setDomain(domainName);
            }
        }
        cookie.setPath("/");
        cookie.setHttpOnly(httpOnly);
        response.addCookie(cookie);
    }

    /**
     * 得到cookie的域名
     */
    public static String getDomainName(HttpServletRequest request) {
        String domainName = null;
        String serverName = request.getRequestURL().toString();

        if (null == serverName || serverName.equals("")) {
            domainName = "";
        } else {
            serverName = serverName.toLowerCase();
            serverName = serverName.substring(7);
            final int end = serverName.indexOf("/");
            serverName = serverName.substring(0, end);
            domainName = serverName;
        }

        if (domainName != null && domainName.indexOf(":") > 0) {
            String[] ary = domainName.split("\\:");
            domainName = ary[0];
        }
        return domainName;
    }

    /**
     * cookie续期（秒）
     */
    public static void expandCookieMaxAge(HttpServletResponse response, Cookie cookie, int expire) {
        cookie.setMaxAge(cookie.getMaxAge() + expire);
        response.addCookie(cookie);
    }

    /**
     * 删除Cookie带cookie域名
     */
    public static void deleteCookie(HttpServletRequest request, HttpServletResponse response, String cookieName) {
        setCookieWithDomain(request, response, cookieName, "", 0);
    }
}
